<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-card class="filter-container" shadow="never">
      <div class="filter-content">
        <el-form :inline="true" :model="listQuery.params" size="small">
          <el-form-item label="题库名称">
            <el-input v-model="listQuery.params.title" placeholder="请输入题库名称" clearable /> 
          </el-form-item>

          <el-form-item label="学校/部门">
            <depart-tree-select 
              v-model="listQuery.params.schoolId" 
              placeholder="请选择学校/部门"
              clearable
              :options="departOptions"
            /> 
          </el-form-item>

          <el-form-item label="科目">
            <el-input v-model="listQuery.params.departType" placeholder="请输入科目名称" clearable /> 
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
            <el-button icon="el-icon-tickets" @click="viewPublicRepoExamRecords">我的考试记录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 题库列表 -->
    <el-card class="list-container" shadow="never">
      <data-table
        ref="pagingTable"
        :options="options"
        :list-query="listQuery"
      >
        <template #data-columns>
          <el-table-column label="题库名称" prop="title" />

          <el-table-column label="科目" prop="departType" width="120" align="center" />

          <el-table-column label="单选题数量" prop="radioCount" width="120" align="center" />

          <el-table-column label="多选题数量" prop="multiCount" width="120" align="center" />

          <el-table-column label="判断题数量" prop="judgeCount" width="120" align="center" />

          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handlePractice(scope.row)">练习模式</el-button>
              <el-button size="mini" type="success" @click="handleExam(scope.row)">考试模式</el-button>
            </template>
          </el-table-column>
        </template>
      </data-table>
    </el-card>
  </div>
</template>

<script>
import DataTable from '@/components/DataTable'
import DepartTreeSelect from '@/components/DepartTreeSelect'
import { fetchTopDepartList } from '@/api/sys/depart/depart'
import { startTrain } from '@/api/user/repo'

export default {
  name: 'PublicRepo',
  components: { DataTable, DepartTreeSelect },
  data() {
    return {
      departOptions: [],
      listQuery: {
        current: 1,
        size: 10,
        params: {
          title: '',
          schoolId: '',
          departType: '',
          onlyPublic: true
        }
      },
      options: {
        // 列表请求URL
        listUrl: '/exam/api/public-repo/paging'
      }
    }
  },
  created() {
    this.fetchData()
    this.fetchDepartList()
  },
  methods: {
    fetchData() {
      // 初始化数据
    },
    handleFilter() {
      this.listQuery.current = 1
      this.$refs.pagingTable.getList()
    },
    resetFilter() {
      this.listQuery.params = {
        title: '',
        schoolId: '',
        departType: '',
        onlyPublic: true
      }
      this.handleFilter()
    },
    handlePractice(row) {
      // 使用练习模式启动训练
      startTrain(0, row.id, this.$store.getters.userId).then(response => {
        if (response.code === 0) {
          // 跳转到题库练习页面，而不是错题训练页面
          this.$router.push({ name: 'RepoTrainingPage', params: { examId: response.data.id } })
        } else {
          this.$message.error(response.msg)
        }
      }).catch(error => {
        console.error('开始练习失败:', error)
        this.$message.error('开始练习失败，请稍后重试')
      })
    },
    handleExam(row) {
      // 使用考试模式启动训练
      startTrain(1, row.id, this.$store.getters.userId).then(response => {
        if (response.code === 0) {
          // 跳转到考试页面
          this.$router.push({ name: 'StartExam', params: { id: response.data.id } })
        } else {
          this.$message.error(response.msg)
        }
      }).catch(error => {
        console.error('开始考试失败:', error)
        this.$message.error('开始考试失败，请稍后重试')
      })
    },
    // 获取顶级部门列表
    fetchDepartList() {
      fetchTopDepartList({}).then(response => {
        // 转换数据格式以适配 DepartTreeSelect 组件
        this.departOptions = response.data.map(item => {
          return {
            rowGuid: item.id,
            areaName: item.deptName,
            parentId: item.parentId
          }
        })
      })
    },
    // 查看公共题库考试记录
    viewPublicRepoExamRecords() {
      this.$router.push({ name: 'PublicRepoRecords' });
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
</style>